const express = require('express');  
const router = express.Router();  
const { User } = require('../../models'); // 确保正确路径  
const bcrypt = require('bcryptjs');  
const jwt = require('jsonwebtoken'); // 用于生成 JSON Web Token  
const {success, failure} = require('../../utils/responses')
const { SequelizeValidationError,UnauthorizedError,JsonWebTokenError,TokenExpiredError,NotFoundError } = require('../../utils/error')



// 登录接口  
router.post('/signin', async (req, res) => {  
  const { phone, password } = req.body;      
  try {  
    
    if (!phone) {
      throw new SequelizeValidationError('手机号必须填写');
    }

    if (!password) {
      throw new SequelizeValidationError('密码必须填写');
    }
    // 查找用户  
    const user = await User.findOne({ where: { phone } });  
    if (!user) {  
      throw new NotFoundError('用户不存在,无法登录');
    }  

    // 验证密码  
    const isPasswordValid = await bcrypt.compare(password, user.password);  
    console.log(password,user.password)
    if (!isPasswordValid) {  
      throw new UnauthorizedError('密码错误,无法登录');
    } 
    
    const role = user.role
    if(role == "0"){
        throw new ForbiddenError('您没有权限登录管理员平台')
    }
    else if(role == 100){
      const token = jwt.sign({ id: user.id}, process.env.SECRET, { expiresIn: '1h' });  
      // 返回成功响应  
      success(res,{
        message: '登录成功',    
        user: {  
          token,
          id: user.id,  
          username: user.username   
        }
      })
    }

  } catch (error) {  
    failure(res,error)  
  }  
});  

module.exports = router;  